package com.novellotus.iov.carvice.activity;

import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.google.gson.JsonObject;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.novellotus.httploadingview.LoadingView;
import com.novellotus.iov.carvice.R;
import com.novellotus.iov.carvice.bean.RxStorageCar;
import com.novellotus.iov.carvice.bean.RxVehicleDetail;
import com.novellotus.iov.carvice.retrofit.BaseEntity;
import com.novellotus.iov.carvice.retrofit.BaseObserver;
import com.novellotus.iov.carvice.retrofit.RetrofitFactory;
import com.novellotus.iov.carvice.retrofit.RxSchedulers;
import com.novellotus.iov.carvice.rxjava.MyObserver;
import com.novellotus.iov.carvice.utils.MyUtils;
import com.novellotus.iov.carvice.utils.MyViewUtils;
import com.novellotus.iov.carvice.utils.SharedPreferencesUtils;
import com.novellotus.iov.carvice.utils.TimeUtils;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.rengwuxian.materialedittext.validation.RegexpValidator;

import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function3;
import okhttp3.RequestBody;

public class AddOutGoingActivity extends BaseActivity implements LoadingView.OnBtnClickListener {

    @BindView(R.id.tv_tittle)
    TextView tv_tittle;
    @BindView(R.id.tv_production_value)
    TextView tv_production_value;
    @BindView(R.id.ln_distributor)
    LinearLayout ln_distributor;
    @BindView(R.id.img_distributor_arrow)
    ImageView img_distributor_arrow;
    @BindView(R.id.ln_client)
    LinearLayout ln_client;
    @BindView(R.id.img_client_arrow)
    ImageView img_client_arrow;
    @BindView(R.id.btn_submit)
    TextView btn_submit;
    @BindView(R.id.edt_plate)
    MaterialEditText edt_plate;
    @BindView(R.id.tv_vin_value)
    TextView tv_vin_value;
    @BindView(R.id.tv_model_value)
    TextView tv_model_value;
    @BindView(R.id.tv_notice_value)
    TextView tv_notice_value;
    //经销商
    @BindView(R.id.edt_certificate)
    EditText edt_certificate;
    @BindView(R.id.edt_invoice)
    EditText edt_invoice;
    @BindView(R.id.edt_distributor)
    EditText edt_distributor;
    @BindView(R.id.edt_distributor_phone)
    EditText edt_distributor_phone;
    @BindView(R.id.tv_get_car_data_value)
    TextView tv_get_car_data_value;
    @BindView(R.id.edt_sale_place)
    EditText edt_sale_place;
    //客户
    @BindView(R.id.edt_client_name)
    EditText edt_client_name;
    @BindView(R.id.edt_client_phone)
    EditText edt_client_phone;
    @BindView(R.id.tv_buy_data_value)
    TextView tv_buy_data_value;
    @BindView(R.id.edt_buy_mile)
    EditText edt_buy_mile;
    @BindView(R.id.edt_postcodes)
    EditText edt_postcodes;
    @BindView(R.id.edt_client_address)
    EditText edt_client_address;
    @BindView(R.id.edt_mark)
    EditText edt_mark;
    @BindView(R.id.edt_distributor_business)
    EditText edt_distributor_business;
    @BindView(R.id.loadingView)
    LoadingView loadingView;
    //    @BindView(R.id.img_vin_arrow)
//    ImageView img_vin_arrow;
    @BindView(R.id.img_out_date_arrow)
    ImageView img_out_date_arrow;
    @BindView(R.id.img_buy_data_arrow)
    ImageView img_buy_data_arrow;
    @BindView(R.id.img_get_date_arrow)
    ImageView img_get_date_arrow;
    @BindView(R.id.tv_base)
    TextView tv_base;
    @BindView(R.id.tv_distributor)
    TextView tv_distributor;
    @BindView(R.id.tv_client)
    TextView tv_client;
    Calendar calendar;
    boolean isShowDistributor = true;
    boolean isShowClient = true;
    String eCode;
    String rCode;
    String carId;
    //车型id
    String typeId;
    //公告型号
    String code;
    //车型名称
    String name;
    String vin;
    String checkPlate = "^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1,2}$";


    @Override
    protected void initContentView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_add_out_goging);
    }

    @Override
    public void init() {

        edt_plate.addValidator(new RegexpValidator("车牌号格式有误", checkPlate));


        calendar = Calendar.getInstance();
        tv_tittle.setText("");
        eCode = getIntent().getStringExtra("eCode");
        rCode = getIntent().getStringExtra("rCode");
        carId = getIntent().getStringExtra("carId");

        if (getIntent().getStringExtra("typeId") != null) {
            typeId = getIntent().getStringExtra("typeId");
            code = getIntent().getStringExtra("code");
            name = getIntent().getStringExtra("name");
            vin = getIntent().getStringExtra("vin");
            tv_vin_value.setText(vin);
            tv_model_value.setText(name);
            tv_notice_value.setText(code);
            loadingView.setVisibility(View.INVISIBLE);
        }
        tv_tittle.setText("新增出库车辆");
        if (carId != null) {
            loadingView.setVisibility(View.VISIBLE);
            loadingView.setLoadingModel(LoadingView.MODEL_ALERT);
            loadingView.setOnBtnClickListener(this);
            loadingView.setBackgroundColor(this.getResources().getColor(R.color.white));
            tv_tittle.setText("出库车辆详情");
            getDetail();
            noFocus();
            btn_submit.setVisibility(View.GONE);
            //  img_vin_arrow.setVisibility(View.GONE);
            img_get_date_arrow.setVisibility(View.GONE);
            img_out_date_arrow.setVisibility(View.GONE);
            img_buy_data_arrow.setVisibility(View.GONE);
            tv_base.setText("基础信息");
            tv_distributor.setText("经销商信息");
            tv_client.setText("客户信息");
        }
        initObservable();

    }

    private void noFocus() {
        edt_plate.setFocusable(false);
        edt_plate.setClickable(false);
        edt_certificate.setFocusable(false);
        edt_invoice.setFocusable(false);
        edt_distributor.setFocusable(false);
        edt_distributor_phone.setFocusable(false);
        edt_sale_place.setFocusable(false);
        edt_client_name.setFocusable(false);
        edt_client_phone.setFocusable(false);
        edt_buy_mile.setFocusable(false);
        edt_postcodes.setFocusable(false);
        edt_client_address.setFocusable(false);
        edt_mark.setFocusable(false);
        edt_distributor_business.setFocusable(false);
    }


    @OnClick(R.id.img_back)
    void back() {
        finish();
    }

    @OnClick(R.id.rlt_distributor)
    void showDistributor() {
        isShowDistributor = !isShowDistributor;
        if (isShowDistributor) {
            img_distributor_arrow.setBackgroundResource(R.mipmap.icon_detail_arrow_down);
            ln_distributor.setVisibility(View.VISIBLE);
        } else {
            img_distributor_arrow.setBackgroundResource(R.mipmap.icon_detail_arrow);
            ln_distributor.setVisibility(View.GONE);
        }

    }

    @OnClick(R.id.rlt_client)
    void showClient() {
        isShowClient = !isShowClient;
        if (isShowClient) {
            img_client_arrow.setBackgroundResource(R.mipmap.icon_detail_arrow_down);
            ln_client.setVisibility(View.VISIBLE);
        } else {
            img_client_arrow.setBackgroundResource(R.mipmap.icon_detail_arrow);
            ln_client.setVisibility(View.GONE);
        }

    }

    @OnClick(R.id.rlt_data)
    void getData() {
        chooseData(tv_production_value);
    }

    @OnClick(R.id.rlt_get_car_data)
    void pickGetCarData() {
        chooseData(tv_get_car_data_value);
    }

    @OnClick(R.id.rlt_buy_data)
    void pickBuyData() {
        chooseData(tv_buy_data_value);
    }

    /**
     * 获取车辆详情
     */
    public void getDetail() {
        Observable<BaseEntity<RxVehicleDetail>> observable = RetrofitFactory.getInstance().vehiclesDetail(carId, SharedPreferencesUtils.getKey(this)[0], eCode, rCode);
        observable.compose(RxSchedulers.<BaseEntity<RxVehicleDetail>>compose())
                .subscribe(new BaseObserver<RxVehicleDetail>(this) {
                    @Override
                    public void onSuccess(RxVehicleDetail t) {
                        loadingView.success();
                        initEdit(t);

                    }

                    @Override
                    public void onFail(int code, String msg) {
                        loadingView.empty(msg, true);
                    }

                    @Override
                    public void onError(String msg) {
                        loadingView.empty(msg, true);
                    }
                });
    }

    private void initEdit(RxVehicleDetail t) {
        tv_vin_value.setText(t.getVin());
        tv_model_value.setText(t.getCarType().getName());
        tv_notice_value.setText(t.getCarType().getCode());
        typeId = t.getCarType().getId();
        edt_plate.setText(t.getPn());
        tv_production_value.setText(t.getProd_date() == 0 ? "" : TimeUtils.StampToDate(t.getProd_date() + ""));
        edt_buy_mile.setText(t.getSell_mileage());
        edt_distributor.setText(t.getDealer_name());
        tv_get_car_data_value.setText(TimeUtils.StampToDate(t.getUser_purchase_date()));
        edt_client_name.setText(t.getUser_name());
        tv_buy_data_value.setText(TimeUtils.StampToDate(t.getReceive_car_date()));
        edt_client_phone.setText(t.getUser_phone());
        edt_client_address.setText(t.getUser_address());
        edt_postcodes.setText(t.getUser_postcode());
        edt_sale_place.setText(t.getAddress());
        edt_distributor_business.setText(t.getContact());
        edt_distributor_phone.setText(t.getContactNumber());
        edt_invoice.setText(t.getInvoiceNumber());
        edt_certificate.setText(t.getCertificate_number());
        edt_mark.setText(t.getRemark());
    }

    /**
     * "pn":"川A17222", 车牌号
     * "prod_date": 1511347228000, 出厂日期 日期类型
     * "sell_mileage": 12.12, 购车里程
     * "dealer_name": "冷氏企业", 经销商名称
     * "receive_car_date": 1511347228000,接车日期
     * "user_name": "冷大叔", 用户姓名单位
     * "user_purchase_date": 1511347228000,购车日期
     * "user_phone": "18380264159",用户电话
     * "user_address": "成都",用户地址
     * "user_postcode": "612023",用户邮编
     * "address": "天府五街",销售地点
     * "contact": "刘德华",经销商业务联系人
     * "contactNumber":"18380264159",经销商业务联系人电话
     * "invoiceNumber": "1283718273",发票号
     * "certificate_number": "123243435",合格证号
     * "remark":"买车了"备注
     */
    @OnClick(R.id.btn_submit)
    void submit() {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("pn", edt_plate.getText().toString());
        jsonObject.addProperty("prod_date", TimeUtils.dateToStamps(tv_production_value.getText().toString()));
        jsonObject.addProperty("sell_mileage", edt_buy_mile.getText().toString());
        jsonObject.addProperty("dealer_name", edt_distributor.getText().toString());
        if (!tv_get_car_data_value.getText().toString().equals("请选择接车日期")) {
            jsonObject.addProperty("receive_car_date", TimeUtils.dateToStamps(tv_get_car_data_value.getText().toString()));
        }
        if (!tv_buy_data_value.getText().toString().equals("请选择购车日期")) {
            jsonObject.addProperty("user_purchase_date", TimeUtils.dateToStamps(tv_buy_data_value.getText().toString()));
        }
        jsonObject.addProperty("user_name", edt_client_name.getText().toString());

        jsonObject.addProperty("user_phone", edt_client_phone.getText().toString());
        jsonObject.addProperty("user_address", edt_client_address.getText().toString());
        jsonObject.addProperty("user_postcode", edt_postcodes.getText().toString());
        jsonObject.addProperty("address", edt_sale_place.getText().toString());
        jsonObject.addProperty("contact", edt_distributor_business.getText().toString());
        jsonObject.addProperty("contactNumber", edt_distributor_phone.getText().toString());
        jsonObject.addProperty("invoiceNumber", edt_invoice.getText().toString());
        jsonObject.addProperty("certificate_number", edt_certificate.getText().toString());
        jsonObject.addProperty("remark", edt_mark.getText().toString());

        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("text/plain; charset=utf-8"), jsonObject.toString());
        Observable<BaseEntity<Object>> observable = RetrofitFactory.getInstance().sale(typeId, SharedPreferencesUtils.getKey(this)[0], eCode, rCode, body);
        observable.compose(RxSchedulers.<BaseEntity<Object>>compose())
                .subscribe(new BaseObserver<Object>(this) {

                    @Override
                    public void onSuccess(Object rxVehicle) {
                        MyUtils.showToast(AddOutGoingActivity.this, "车辆出库成功");
                        finish();
                    }

                    @Override
                    public void onFail(int code, String msg) {
                        MyUtils.showToast(AddOutGoingActivity.this, msg);
                    }

                    @Override
                    public void onError(String msg) {
                        MyUtils.showToast(AddOutGoingActivity.this, msg);
                    }
                });
    }

    /**
     * 获取已经入库车辆
     */
//    List<RxStorageCar.RecordsBean> rxStorageCarList;
//    private void getStorage() {
//        Observable<BaseEntity<RxStorageCar>> observable = RetrofitFactory.getInstance().getStorage(SharedPreferencesUtils.getKey(this)[0], eCode, rCode, 1000, 1);
//        observable.compose(RxSchedulers.<BaseEntity<RxStorageCar>>compose())
//                .subscribe(new BaseObserver<RxStorageCar>(this) {
//                    @Override
//                    public void onSuccess(RxStorageCar rxStorageCar) {
//                        loadingView.success();
//                        rxStorageCarList = rxStorageCar.getRecords();
//                        if (vin != null) {
//                            for (RxStorageCar.RecordsBean recordsBean : rxStorageCarList) {
//                                if (vin.equals(recordsBean.getVin())) {
//                                    tv_vin_value.setText(recordsBean.getVin());
//                                    tv_model_value.setText(recordsBean.getName());
//                                    tv_notice_value.setText(recordsBean.getCode());
//                                    typeId = recordsBean.getId();
//                                }
//                            }
//                        }
//                    }
//
//                    @Override
//                    public void onFail(int code, String msg) {
//                        loadingView.empty(msg, true);
//                    }
//
//                    @Override
//                    public void onError(String msg) {
//                        loadingView.empty(msg, true);
//                    }
//                });
//    }

    //  @OnClick(R.id.rlt_vin)
//    public void showPicker() {
//        if (carId == null) {
//            if (rxStorageCarList != null) {
//                if (rxStorageCarList.size() == 0) {
//                    MyUtils.showToast(this, "暂无数据上报车辆");
//                } else {
//                    OptionsPickerView pvOptions = new OptionsPickerView.Builder(AddOutGoingActivity.this, new OptionsPickerView.OnOptionsSelectListener() {
//                        @Override
//                        public void onOptionsSelect(int options1, int options2, View v) {
//                            tv_vin_value.setText(rxStorageCarList.get(options1).getVin());
//                            tv_model_value.setText(rxStorageCarList.get(options1).getName());
//                            tv_notice_value.setText(rxStorageCarList.get(options1).getCode());
//                            typeId = rxStorageCarList.get(options1).getId();
//                        }
//                    })
//                            .setTitleText("选择车辆识别代码")
//                            .setDividerColor(Color.BLACK)
//                            .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
//                            .setContentTextSize(20)
//                            .setOutSideCancelable(false)// default is truet
//                            .build();
//                    pvOptions.setPicker(rxStorageCarList);
//                    pvOptions.show();
//                }
//
//            } else {
//                getStorage();
//            }
//        }
//
//    }


    void chooseData(final TextView tv) {
        MyUtils.hideInput(this);
        if (carId == null) {
            final DatePicker date = new DatePicker(AddOutGoingActivity.this);
            date.setCalendarViewShown(false);
            date.init(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), new DatePicker.OnDateChangedListener() {
                @Override
                public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                }
            });
            AlertDialog.Builder mDatePickerDialogBuilder = new AlertDialog.Builder(AddOutGoingActivity.this);
            mDatePickerDialogBuilder.setView(date);
            mDatePickerDialogBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (System.currentTimeMillis() < TimeUtils.dateToStamps(date.getYear() + "-" + (date.getMonth() + 1) + "-" + date.getDayOfMonth())) {
                        MyUtils.showToast(AddOutGoingActivity.this, "选择日期不能大于当前时间");
                    } else {
                        //只有点击确定按钮时，才更改时间，并设置在文本中显示
                        int year = date.getYear();
                        int month = date.getMonth() + 1;
                        int day = date.getDayOfMonth();
                        String monthStr;
                        if (month < 10) {
                            monthStr = "0" + month;
                        } else {
                            monthStr = month + "";
                        }
                        String dayStr;
                        if (day < 10) {
                            dayStr = "0" + day;
                        } else {
                            dayStr = day + "";
                        }
                        tv.setText(year + "-" + monthStr + "-" + dayStr);
                    }

                }
            });
            mDatePickerDialogBuilder.setNegativeButton("取消", null);
            mDatePickerDialogBuilder.show();
        }

    }

    /**
     * 表单验证
     */
    private Observable<CharSequence> ObservablePlate;
    private Observable<CharSequence> ObservableVin;
    private Observable<CharSequence> ObservableDate;

    private void initObservable() {
        ObservablePlate = RxTextView.textChanges(edt_plate);
        ObservablePlate.compose(RxSchedulers.<CharSequence>lifecycle(this))
                .compose(RxSchedulers.<CharSequence>compose())
                .subscribe(new MyObserver<CharSequence>() {
                    @Override
                    public void onNext(CharSequence pass) {
                        super.onNext(pass);
                        if (pass.length() >= 7) {
                            edt_plate.validate();
                        }
                    }
                });
        ObservableVin = RxTextView.textChanges(tv_vin_value);
        ObservableDate = RxTextView.textChanges(tv_production_value);
        Observable.combineLatest(ObservablePlate, ObservableVin, ObservableDate, new Function3<CharSequence, CharSequence, CharSequence, Boolean>() {
            @Override
            public Boolean apply(CharSequence plate, CharSequence vin, CharSequence date) throws Exception {
                return MyUtils.isPlate(plate.toString()) && vin.length() == 17 && (!date.toString().equals("请选择出厂日期") && !date.toString().equals(""));
            }
        }).compose(RxSchedulers.<Boolean>lifecycle(AddOutGoingActivity.this)).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean pass) throws Exception {
                if (pass) {
                    MyViewUtils.setButtonClickable(btn_submit, true);
                } else {
                    MyViewUtils.setButtonClickable(btn_submit, false);
                }
            }
        });
    }

    @Override
    public void onReload() {
        getDetail();
    }
}
